import { Component, OnInit } from '@angular/core';
import { NavController, ToastController } from 'ionic-angular';

import { TasksService } from './tasks.service';
import { TasksResponse, ApproveTaskResponse } from '../../app/app.service';
import { DetailPage } from './detail/detail';

@Component({
    selector: 'tasks-page',
    templateUrl: 'tasks.html'
})
export class TasksPage implements OnInit {

    tasksList: Array<any>;
    orignList: Array<any>;
    tasksNum: number;
    lastOpenItem: any;
    toast: any;

    constructor(public navCtrl: NavController, private tasksService: TasksService, private toastCtrl: ToastController) { }

    ngOnInit() {
        this.orignList = [];
        this.tasksList = [];
        this.tasksNum = 0;
        this.tasksService.getAllTask()
            .then((res: TasksResponse) => {
                if (res.code === 'SUCCESS') {
                    this.tasksNum = res.data.total;
                    this.orignList = res.data.list;
                    this.tasksList = res.data.list;
                } else if (res.devMsg === 'TOKEN_TIME_OUT') {
                    this.toast = this.toastCtrl.create({
                        message: res.userMsg,
                        duration: 1000
                    });
                    this.toast.present();

                    this.navCtrl.parent.parent.pop();
                    
                }

            });
    }

    ionViewWillEnter() {

    }

    ionViewWillLeave() {

    }

    itemOnSwipe(e) {
        if (typeof this.lastOpenItem !== 'undefined' && this.lastOpenItem !== e.target) {
            this.lastOpenItem.classList.remove('open');
            this.lastOpenItem = undefined;
        }
        if (e.deltaX < 0) {
            e.target.classList.add('open');
            this.lastOpenItem = e.target;
        } else {
            e.target.classList.remove('open');
        }
    }
    itemTapped(item) {
        if (typeof this.lastOpenItem !== 'undefined') {
            this.lastOpenItem.classList.remove('open');
            this.lastOpenItem = undefined;
        }
        this.navCtrl.push(DetailPage, item);
    }

    onSearch(key: string) {
        console.log(key);
        if (key.length === 0) {
            this.tasksList = this.orignList;
        } else {
            this.tasksList = this.tasksService.search(key, this.orignList);
        }
    }
    rejectTapped(task) {
        console.log('拒绝');
        this.tasksService.rejectTask(`${task.task_id}`)
            .then((res: ApproveTaskResponse) => {

            });
    }
    approveTapped(task) {
        console.log('同意');
        this.tasksService.approveTask(`${task.task_id}`)
            .then((res: ApproveTaskResponse) => {

            });
    }

}
